cmake_minimum_required(VERSION 3.12)
project(GasSensor C CXX ASM)

# 工具链设置
set(CMAKE_SYSTEM_NAME Generic)
set(CMAKE_SYSTEM_PROCESSOR arm)
set(CMAKE_C_COMPILER arm-none-eabi-gcc)
set(CMAKE_CXX_COMPILER arm-none-eabi-g++)
set(CMAKE_ASM_COMPILER arm-none-eabi-gcc)
set(CMAKE_OBJCOPY arm-none-eabi-objcopy)
set(CMAKE_SIZE arm-none-eabi-size)

add_definitions(
        -DPY32F002Bx5
        -DUSE_FULL_LL_DRIVER
)

# 微控制器配置
set(MCU_CPU cortex-m0plus)
set(MCU_FPU soft)
set(MCU_ARCH armv6s-m)  # 新增架构指定

# 编译选项（分项设置）
add_compile_options(
        -mcpu=${MCU_CPU}
        -march=${MCU_ARCH}
        -mthumb
        -mfloat-abi=${MCU_FPU}
        -Os
        -ffunction-sections
        -fdata-sections
        -fstack-usage
        -Wall
        -specs=nano.specs
        -specs=nosys.specs
)

# 链接选项（分项设置）
add_link_options(
        -mcpu=${MCU_CPU}
        -march=${MCU_ARCH}
        -mthumb
        -mfloat-abi=${MCU_FPU}
        -Wl,--gc-sections
        -Wl,-Map=${PROJECT_NAME}.map
        -T${CMAKE_SOURCE_DIR}/Drivers/LD/py32f002bx5.ld
        -specs=nano.specs
        -specs=nosys.specs
)

# 包含目录
include_directories(
        ${CMAKE_SOURCE_DIR}/Drivers/CMSIS/Include
        ${CMAKE_SOURCE_DIR}/Drivers/PY32F002B_HAL_Driver/Inc/
        ${CMAKE_SOURCE_DIR}/Core/Inc
        ${CMAKE_SOURCE_DIR}/User/Main/Inc
        ${CMAKE_SOURCE_DIR}/User/Hal/Inc
        ${CMAKE_SOURCE_DIR}/User/Alg/Inc
)

# 源文件
file(GLOB_RECURSE SOURCES
        "Core/Src/*.c"
        "Drivers/PY32F002B_HAL_Driver/Src/*.c"
        "User/Main/Src/*.c"
        "User/Main/Src/*.c"
        "User/Hal/Src/*.c"
        "User/Alg/Src/*.c"
)

# 启动文件
set(STARTUP_ASM_FILE "${CMAKE_SOURCE_DIR}/Core/Src/startup_py32f002bxx.s")

# 生成可执行文件
add_executable(${PROJECT_NAME}.elf
        ${SOURCES}
        ${STARTUP_ASM_FILE}
)

# 生成hex和bin文件
add_custom_command(TARGET ${PROJECT_NAME}.elf POST_BUILD
        COMMAND ${CMAKE_OBJCOPY} -O ihex ${PROJECT_NAME}.elf ${PROJECT_NAME}.hex
        COMMAND ${CMAKE_OBJCOPY} -O binary -S ${PROJECT_NAME}.elf ${PROJECT_NAME}.bin
        COMMENT "Generating HEX and BIN files"
)

# 显示大小信息
add_custom_command(TARGET ${PROJECT_NAME}.elf POST_BUILD
        COMMAND ${CMAKE_SIZE} --format=berkeley $<TARGET_FILE:${PROJECT_NAME}.elf>
        COMMENT "Memory usage:"
)

add_custom_target(flash
        COMMAND pyocd flash --target PY32F002Bx5 $<TARGET_FILE:${PROJECT_NAME}.elf>
        DEPENDS ${PROJECT_NAME}.elf
        COMMENT "Flashing GasSensor firmware to PY32F002Bx5"
)